#include "BufMgr.h"
#include "MemPool.h"
#include "BufBlockMgr.h"
#include "BufChunkMgr.h"

CBufMgr::CBufMgr(/* args */)
{
    m_pChunks = nullptr;
    m_pBlocks = nullptr;
}

CBufMgr::~CBufMgr()
{
    Destroy();
}

void *CBufMgr::operator new(size_t sz)
{
    CMemPool *mp = CMemPool::GetInstance();

    if (nullptr == mp)
        return NULL;

    return mp->Alloc(sz);
}

void CBufMgr::operator delete(void *ptr)
{
    CMemPool *mp = CMemPool::GetInstance();

    if (nullptr != mp)
        mp->Free(ptr);
}

bool CBufMgr::Init()
{
    m_pChunks = new CBufChunkMgr();

    if (nullptr == m_pChunks)
        return false;

    m_pBlocks = new CBufBlockMgr(m_pChunks);

    if (nullptr == m_pBlocks)
    {
        delete m_pChunks;
        m_pChunks = nullptr;
        return false;
    }

    return true;
}

void CBufMgr::Destroy()
{
    if (nullptr != m_pBlocks)
    {
        m_pBlocks->Destroy();
        delete m_pBlocks;
        m_pBlocks = nullptr;
    }

    if (nullptr != m_pChunks)
    {
        m_pChunks->Destroy();
        delete m_pChunks;
        m_pChunks = nullptr;
    }
}

BufBlockNode *CBufMgr::GetBlock()
{
    return (nullptr != m_pBlocks) ? m_pBlocks->GetBlock() : nullptr;
}

bool CBufMgr::FreeBlock(BufBlockNode *pNode)
{
    return (nullptr != m_pBlocks) ? m_pBlocks->FreeBlock(pNode) : false;
}